﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using UnityEngine.UI;
using UnityEngine.Events;
using System.Text.RegularExpressions;
using Object = UnityEngine.Object;

public static class UIMenu
{
    // 筛选文件正则预设
    private const string SEARCH_PREFAB = @".*\.prefab$";
    private const string SEARCH_META = @".*\.meta$";

    // 批量处理警告数量，当处理对象超过该数值，需要请求确认是否继续
    private const int WARNING_COUNT = 10;

    /// <summary>
    /// 批量处理鼠标选中 Project 对象
    /// 可以单选，多选，以及选择文件夹，包括混选
    /// </summary>
    /// <param name="tag">任务标题</param>
    /// <param name="callback">任务回调</param>
    /// <param name="pattern">匹配文件正则规则</param>
    /// <param name="option">搜索选项</param>
    public static void TraversalFiles(string tag, UnityAction<string> callback, string pattern, SearchOption option = SearchOption.TopDirectoryOnly)
    {
        EditorUtility.ClearProgressBar();

        var items = Selection.assetGUIDs;
        if (items.Length <= 0)
        {
            Debug.Log(string.Format("【{0}】: Finish", tag));
            return;
        }

        var matchItem = new HashSet<string>();
        var r = new Regex(pattern);

        for (var i = 0; i < items.Length; ++i)
        {
            var path = AssetDatabase.GUIDToAssetPath(items[i]);

            if (r.IsMatch(path))
            {
                if (!matchItem.Contains(path))
                {
                    matchItem.Add(path);
                }
            }
            else if (Directory.Exists(path))
            {
                var allPath = Directory.GetFiles(path, "*.*", option);
                foreach (var item in allPath)
                {
                    if (r.IsMatch(item))
                    {
                        if (!matchItem.Contains(item))
                        {
                            matchItem.Add(item);
                        }
                    }
                }
            }
        }

        var isDirty = false;
        if (matchItem.Count < WARNING_COUNT
            ||
            EditorUtility.DisplayDialog(tag, string.Format("Warning: 即将处理的对象有: {0}，可能会非常耗时，是否继续？", matchItem.Count), "Ok", "Cancel"))
        {
            try
            {
                var i = 0;
                foreach (var item in matchItem)
                {
                    ++i;
                    isDirty = true;
                    var itemName = Path.GetFileName(item);
                    var msg = string.Format("Progressing({0}/{1}: {2}", i, matchItem.Count, itemName);
                    if (EditorUtility.DisplayCancelableProgressBar(tag, msg, (float)i / matchItem.Count))
                    {
                        Debug.Log(string.Format("【{0}】: User Cancel", tag));
                        break;
                    }
                    else
                    {
                        callback(item);
                    }
                }
            }
            catch (Exception e)
            {
                EditorUtility.DisplayDialog(tag, "Fail!!!, cancel progress. Please check error message in console", "Ok");
                Debug.LogError(string.Format("【{0}】: {1}", tag, e.ToString()));
            }
        }
        else
        {
            Debug.Log(string.Format("【{0}】: User Cancel", tag));
            EditorUtility.ClearProgressBar();

            return;
        }

        Debug.Log(string.Format("【{0}】: Finish", tag));
        EditorUtility.ClearProgressBar();
        if (isDirty)
        {
            AssetDatabase.Refresh();
        }
    }

    /// <summary>
    /// 运行cmd命令
    /// 不显示命令窗口
    /// </summary>
    /// <param name="cmdExe">指定应用程序的完整路径</param>
    /// <param name="cmdStr">执行命令行参数</param>
    static bool RunCmd(string command)
    {
        //Debug.Log(command);
        var result = false;
        try
        {
            using (var p = new System.Diagnostics.Process())
            {

                p.StartInfo.FileName = "cmd.exe";
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.Arguments = "/c " + command;//“/C”表示执行完命令后马上退出  
                p.Start();//执行 

                //p.StandardInput.WriteLine(command + "&exit");
                //p.StandardInput.AutoFlush = true;


                //获取cmd窗口的输出信息
                //string output = p.StandardOutput.ReadToEnd();

                //Debug.Log("result:" + output);

                p.WaitForExit();
                p.Close();

                result = true;
            }
        }
        catch
        {
            Debug.Log("exception:" + command);
        }
        return result;
    }

   

    [MenuItem("Assets/复制Sprite路径",false,10000)]
    private static void CopySpritePath()
    {
        var obj = Selection.activeObject;
        var path = AssetDatabase.GetAssetPath(obj);
        var fileName = Path.GetFileName(path);
        var fileNameWTEx = Path.GetFileNameWithoutExtension(fileName);
        var finalStr = '"' + fileNameWTEx + '"' + "," + '"' + obj.name + '"';
        GUIUtility.systemCopyBuffer = finalStr;
        Debug.Log($"{finalStr} is copied to clipboard");
    }


    [MenuItem("Assets/zlnken测试", false, 10001)]
    private static void ZhenkeTest()
    {
        //var obj = Selection.activeObject;
        //var path = AssetDatabase.GetAssetPath(obj);
        //var fileName = Path.GetFileName(path);
        //var fileNameWTEx = Path.GetFileNameWithoutExtension(fileName);
        //var finalStr = '"' + fileNameWTEx + '"' + "," + '"' + obj.name + '"';
        //GUIUtility.systemCopyBuffer = finalStr;
        //Debug.Log($"{finalStr} is copied to clipboard");

        Debug.Log("zlnken测试");
    }

}
